﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using Google.GData.Contacts;
using Google.Contacts;
using Google.GData.Client;
using Google.GData.Extensions;

namespace GoogleContacts
{
    public partial class Contacts : Form
    {
        ContactsService _service = new ContactsService("google-anagrafica");
        string _token = "";
        int startIndex = 1;

        public Contacts()
        {
            InitializeComponent();
        }

        private void btn_login_Click(object sender, EventArgs e)
        {
            try
            {
                _service.setUserCredentials(txt_mail.Text, txt_password.Text);
                _token = _service.QueryClientLoginToken();
                btn_getContacts.Enabled = true;
                btn_login.Enabled = false;
                txt_mail.Enabled = false;
                txt_password.Enabled = false;

                MessageBox.Show("Login OK");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btn_getContacts_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;

                dgv_rubrica.Visible = false;
                dgv_rubrica.Rows.Clear();
                dgv_rubrica.Columns.Clear();
                dgv_rubrica.Columns.Add("Nome", "Nome");
                dgv_rubrica.Columns.Add("Telefono", "Telefono");
                dgv_rubrica.Columns.Add("Id", "Id");

                dgv_telefoni.Columns.Add("Numero", "Numero");

                GetContact();

                dgv_rubrica.Visible = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        private void GetContact()
        {
            ContactsQuery query = new ContactsQuery(ContactsQuery.CreateContactsUri("default"));
            query.StartIndex = startIndex;

            ContactsFeed feed = _service.Query(query);

            while (feed != null && feed.Entries.Count > 0)
            {
                foreach (ContactEntry entry in feed.Entries)
                {
                    if (entry.Phonenumbers.Count > 0)
                    {
                        string telefoni = "";
                        for (int a = 0; a < entry.Phonenumbers.Count; a++)
                        {
                            telefoni += entry.Phonenumbers[a].Value + "; ";
                        }

                        int x = telefoni.LastIndexOf(";");
                        telefoni = telefoni.Substring(0, telefoni.LastIndexOf(";"));

                        string[] rubr = { entry.Name == null ? "" : entry.Name.FullName, telefoni, entry.Id.AbsoluteUri };
                        dgv_rubrica.Rows.Add(rubr);
                    }
                }

                if (feed.NextChunk != null)
                {
                    query.Uri = new Uri(feed.NextChunk);
                    feed = _service.Query(query) as ContactsFeed;
                }
                else
                    feed = null;
            }

            dgv_rubrica.Sort(dgv_rubrica.Columns[0], ListSortDirection.Ascending);
        }

        private void dgv_rubrica_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                //if (e.ColumnIndex == 2)
                {
                    string qr = dgv_rubrica.Rows[e.RowIndex].Cells[2].Value.ToString().Replace("base", "full");
                    GDataCredentials Credentials = new GDataCredentials(txt_mail.Text, txt_password.Text);
                    RequestSettings settings = new RequestSettings("Rubrica", Credentials);
                    settings.UseSSL = true;

                    ContactsRequest cr = new ContactsRequest(settings);
                    Contact contatto = cr.Retrieve<Contact>(new Uri(qr));
                    DownloadPhoto(cr, contatto.PhotoUri);

                    string[] tels = dgv_rubrica.Rows[e.RowIndex].Cells[1].Value.ToString().Split(';');
                    dgv_telefoni.Rows.Clear();

                    for (int i = 0; i < tels.Length; i++)
                    {
                        string[] dd = new string[1];
                        dd[0] = tels[i];
                        dgv_telefoni.Rows.Add(dd);
                    }

                    dgv_telefoni.Visible = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        public void DownloadPhoto(ContactsRequest cr, Uri PhotoUri)
        {
            try
            {
                Image img = Image.FromStream(cr.Service.Query(PhotoUri));
                pcb_foto.Image = img; 
            }
            catch (Exception ex)
            {
                pcb_foto.Image = null;
            }
        }

        private void Contacts_Load(object sender, EventArgs e)
        {
            this.Text += " - "+System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
            linkLabel1.Links.Add(0, 44, "https://support.google.com/mail/answer/1173270?hl=en");
        }

        private void linkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            System.Diagnostics.Process.Start(e.Link.LinkData.ToString());
        }

    }
}
